package com.example.controller;

import com.example.pojo.User;
import com.example.service.UserManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 * 提供用户模糊搜索、添加和删除的接口
 */
@RestController
@RequestMapping("/api/userManagement")
public class UserManagementController {

    @Autowired
    private UserManagementService userManagementService;

    /**
     * 分页模糊搜索用户
     *
     * @param keyword 查询关键字（用户名）
     * @param page    当前页码，从1开始
     * @param size    每页条数
     * @return 查询结果列表和总数
     */
    @GetMapping("/search")
    public Map<String, Object> searchUsers(
            @RequestParam(defaultValue = "") String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        List<User> userList = userManagementService.searchUsers(keyword, page, size);
        int total = userManagementService.countUsers(keyword);

        Map<String, Object> result = new HashMap<>();
        result.put("data", userList);
        result.put("total", total);
        return result;
    }

    /**
     * 添加新用户
     *
     * @param user 用户信息，只需传 username, email, power
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public Map<String, Object> addUser(@RequestBody User user) {
        boolean success = userManagementService.addUser(user);

        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        return result;
    }

    /**
     * 根据ID删除用户
     *
     * @param id 用户ID
     * @return 是否删除成功
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteUser(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userManagementService.deleteUser(id);
            result.put("success", success);
            if (!success) {
                result.put("message", "该用户有未归还书籍，无法删除。");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器错误，请稍后再试");
        }
        return result;
    }
}